package com.config;

import cn.hutool.core.lang.Snowflake;
import com.security.*;
import com.service.UserService;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import java.security.Key;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    UserService userService;
    @Autowired
    LoginAuthenticationFilter loginAuthenticationFilter;
    @Autowired
    TokenAuthenticationFilter tokenAuthenticationFilter;
    @Autowired
    UserPasswordAuthenticationProvider userPasswordAuthenticationProvider;
    @Autowired
    OtpAuthenticationProvider otpAuthenticationProvider;
    String key = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //向认证管理器注册认证提供者
        auth.authenticationProvider(userPasswordAuthenticationProvider)
                .authenticationProvider(otpAuthenticationProvider);

    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/login", "/**", "/2/api-docs/**", "/swagger-ui.html/**", "webjars/**", "/user/**", "/css/**", "/js/**", "/lib/**", "images/**", "/api/**", "/page/**");
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public CustomSigningKeyResolver customSigningKeyResolver() {    //为每一个用户生成一个密钥
        List<Long> userList = userService.findAllUserIds();
        Map<String, Key> map = new HashMap<>();
        userList.stream().forEach(u -> {
//                    map.put(u.toString(), Keys.secretKeyFor(SignatureAlgorithm.HS256));
            map.put(u.toString(), Keys.hmacShaKeyFor(key.getBytes()));
        });

        return new CustomSigningKeyResolver(map);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //禁用form和basic认证
        http.httpBasic().disable();
        http.formLogin().disable();
        //注册自定义过滤器
        http.addFilterAt(loginAuthenticationFilter, BasicAuthenticationFilter.class);
        http.addFilterAfter(tokenAuthenticationFilter, BasicAuthenticationFilter.class);
        //跨域令牌伪造
        http.csrf().disable();
        //所有访问都需要认证
        http.cors().and().authorizeRequests().anyRequest().authenticated()
                .anyRequest().access("@accessControlCheck.checkPermission(request,authentication)");//检查权限
    }

    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public Snowflake snowflake() {
        return new Snowflake(1, 1);
    }
}
